/**
 * SpringMVC restful 风格
 * 购买过程 控制器，控制关于购物车,订单，支付的一些业务逻辑操作
 * @author WangXinLei
 * @date 2014-09-12
 */
package com.chnbst.bstyun.controller.user;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.CreateOrderNum;
import com.chnbst.bstyun.core.common.DateUtil;
import com.chnbst.bstyun.core.common.PriceUtil;
import com.chnbst.bstyun.core.common.ReadProperties;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.core.common.email.EmailUtil;
import com.chnbst.bstyun.eos.CreateNum;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Cashflow;
import com.chnbst.bstyun.model.pojo.Deal;
import com.chnbst.bstyun.model.pojo.Email;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.GoodsRelation;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Payment;
import com.chnbst.bstyun.model.pojo.ShoppingCart;
import com.chnbst.bstyun.model.pojo.Supplier;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.pojo.Voucher;
import com.chnbst.bstyun.model.vo.GoodsVo;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.model.vo.ShoppingCartVo;
import com.chnbst.bstyun.service.CashflowService;
import com.chnbst.bstyun.service.DealService;
import com.chnbst.bstyun.service.EmailService;
import com.chnbst.bstyun.service.GoodsFeeService;
import com.chnbst.bstyun.service.GoodsRelationService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PaymentService;
import com.chnbst.bstyun.service.ShoppingCartService;
import com.chnbst.bstyun.service.SupplierService;
import com.chnbst.bstyun.service.UserService;
import com.chnbst.bstyun.service.VoucherService;
//import com.chnbst.mail.EmailUtil;

/**
 * 控制器注解 请求映射注解 controller 代表类是控制器 restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 */
@Controller
@RequestMapping("/buy")
public class BuyProcessController {
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired 
	private ShoppingCartService shoppingCartService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired 
	private DealService dealService;
	@Autowired
	private VoucherService voucherService;
	@Autowired
	private CashflowService cashflowService;
	@Autowired 
	private Eos eos;
	@Autowired
	private CreateNum createNum;
	@Autowired
	private ReadProperties readProperties;
	@Autowired 
	private PaymentService paymentService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsFeeService goodsFeeService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private GoodsRelationService goodsRelationService;
	@Autowired
	private EmailService emailService;
	
	private static final String ROLE_COMPANY = "ROLE_COMPANY";//公司用户
	private static final String ROLE_PERSON = "ROLE_PERSON";//个人用户
	private static final String ROLE_AGENT = "ROLE_AGENT";//代理商
	
	/**
	 * @return 加入购物车
	 * @throws Exception
	 */
	@RequestMapping(value = "/shoppingCart/add", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addShoppingCart(String goodsId,Integer useYear,Integer userNum,HttpServletRequest request) throws Exception {
		User user = (User)request.getSession().getAttribute("userInfo");
		
		GoodsVo goodsVo = goodsService.selectGoodsVoByGoodsId(goodsId);
		
		ShoppingCart shoppingCart = new ShoppingCart();
		shoppingCart.setAddTime(new Date());
		shoppingCart.setIsDelete(0);
		shoppingCart.setUserNum(userNum);
		shoppingCart.setUserId(user.getUserId());
		String useLife = "";
		if(useYear == 0){
			useLife = "20天";
		}else{
			useLife = useYear.toString();
		}
		shoppingCart.setUseLife(useLife);
		if(useYear == -1) useYear = 1;
		else useYear = useYear * 12;
		Double proMealPrice = PriceUtil.calculatePrice(goodsVo.getGoodsPrice(), useYear, userNum, goodsVo.getFeeFormula(), goodsVo.getFeeBasenum());
		shoppingCart.setProMealPrice(proMealPrice);
		shoppingCart.setProMealNum(1);
		shoppingCart.setProMealId(goodsId);
		
		boolean isSuccess = shoppingCartService.insertShoppingCart(shoppingCart);
		
		Map<String, Object> cartInfo = shoppingCartService.selectShoppingCartCountByUserId(user.getUserId());
		if(cartInfo.get("sumPrice") == null) cartInfo.put("sumPrice", 0.0);
		request.getSession().setAttribute("cartInfo",cartInfo);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("isSuccess", isSuccess);
		map.put("sumNum", cartInfo.get("sumNum"));
		map.put("sumPrice", cartInfo.get("sumPrice"));
		map.put("goodsName", goodsVo.getGoodsName());
		return map;
	}
	
	/**
	 * 点击立即购买
	 * @param goodsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/haveRelation", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> haveRelation(String goodsId,Integer useYear,Integer userNum,Integer pageNum,HttpServletRequest request) throws Exception {
		boolean hasRelation = false;
		boolean hasBuy = false;
		boolean isFree = false;
		boolean isBuy = false;
		Map<String, Object> map = new HashMap<String, Object>();
		//查询当前用户信息
		User oldUserInfo = (User) request.getSession().getAttribute("userInfo");
		User userInfo = userService.selectUserInfoByUserId(oldUserInfo.getUserId());
		Integer userId = userInfo.getUserId();
		String roleId = userInfo.getRoleId();
		List<OrderVo> orderList = new ArrayList<OrderVo>();
		//查询当前所要购买的商品的信息，判断依赖关系是否存在
		GoodsVo goodsVo = goodsService.selectGoodsVoByGoodsId(goodsId);
		List<GoodsRelation> goodsRelationList = new ArrayList<GoodsRelation>();
		goodsRelationList = goodsRelationService.selectByGoodsId(goodsId);
		for (int i = 0; i < goodsRelationList.size(); i++) {
			if(goodsVo.getGoodsNames() == null){
				goodsVo.setGoodsNames(goodsRelationList.get(i).getProductName());
			}else{
				goodsVo.setGoodsNames(goodsVo.getGoodsNames() +","+ goodsRelationList.get(i).getProductName());
			}
			if(goodsVo.getGoodsNums() == null){
				goodsVo.setGoodsNums(goodsRelationList.get(i).getProductNum());
			}else{
				goodsVo.setGoodsNums(goodsVo.getGoodsNums() +","+ goodsRelationList.get(i).getProductNum());
			}
		}
		//所依赖产品的信息
		Goods goods = new Goods();
		
		if(!goodsVo.getGoodsRalateGoods().equals("0")){
			//依赖关系存在，查询所依赖的商品是否有新购订单
			hasRelation = true;
			//根据角色不同传入不同的参数
			//个人用户
			if(roleId.equals(ROLE_PERSON)){
				goods = goodsService.selectGoodsVoByGoodsId(goodsVo.getGoodsRalateGoods());
				Map<String, Object> _map = new HashMap<String, Object>();
				_map.put("goodsId", goodsVo.getGoodsRalateGoods());
				_map.put("userId", userId);
				_map.put("roleId", ROLE_PERSON);
				_map.put("sortField", "t.pay_time");
				_map.put("sortOrder", "desc");
				orderList = orderService.relationHasOrder(_map);
				if(orderList != null && orderList.size() > 0){
					
					for (int i = 0; i < orderList.size(); i++) {
						OrderVo orderVo = orderList.get(i);
						String relationId = orderVo.getGoodsId();
						List<GoodsRelation> goodsReList = new ArrayList<GoodsRelation>();
						goodsReList = goodsRelationService.selectByGoodsId(relationId);
						for (int j = 0; j < goodsReList.size(); j++) {
							if(orderVo.getGoodsNames() == null){
								orderVo.setGoodsNames(goodsReList.get(j).getProductName());
							}else{
								orderVo.setGoodsNames(orderVo.getGoodsNames() +","+ goodsReList.get(j).getProductName());
							}
							if(orderVo.getGoodsNums() == null){
								orderVo.setGoodsNums(goodsReList.get(j).getProductNum());
							}else{
								orderVo.setGoodsNums(orderVo.getGoodsNums() +","+ goodsReList.get(j).getProductNum());
							}
						}
					}
					//依赖订单存在，判断是否是免费
					hasBuy = true;
					if(orderList.get(0).getIsFree() == 1){
						isFree = true;
					}
				}
				
			//代理商用户
			}else if(roleId.equals(ROLE_AGENT)){
				goods = goodsService.selectGoodsVoByGoodsId(goodsVo.getGoodsRalateGoods());
				Map<String, Object> _map = new HashMap<String, Object>();
				_map.put("goodsId", goodsVo.getGoodsRalateGoods());
				_map.put("userId", userId);
				_map.put("roleId", ROLE_AGENT);
				orderList = orderService.relationHasOrder(_map);
				if(orderList != null && orderList.size() > 0){
					
					for (int i = 0; i < orderList.size(); i++) {
						OrderVo orderVo = orderList.get(i);
						String relationId = orderVo.getGoodsId();
						List<GoodsRelation> goodsReList = new ArrayList<GoodsRelation>();
						goodsReList = goodsRelationService.selectByGoodsId(relationId);
						for (int j = 0; j < goodsReList.size(); j++) {
							if(orderVo.getGoodsNames() == null){
								orderVo.setGoodsNames(goodsReList.get(j).getProductName());
							}else{
								orderVo.setGoodsNames(orderVo.getGoodsNames() +","+ goodsReList.get(j).getProductName());
							}
							if(orderVo.getGoodsNums() == null){
								orderVo.setGoodsNums(goodsReList.get(j).getProductNum());
							}else{
								orderVo.setGoodsNums(orderVo.getGoodsNums() +","+ goodsReList.get(j).getProductNum());
							}
						}
					}
					//依赖订单存在
					hasBuy = true;
				}
			}else if(roleId.equals(ROLE_COMPANY)){
				Map<String, Object> _map = new HashMap<String, Object>();
				_map.put("goodsId", goodsVo.getGoodsRalateGoods());
				_map.put("userId", userId);
				_map.put("roleId", ROLE_COMPANY);
				orderList = orderService.relationHasOrder(_map);
				if(orderList != null && orderList.size() > 0){
					//依赖订单存在，判断是否是免费
					hasBuy = true;
					
					_map.put("goodsId", goodsVo.getGoodsId());
					_map.put("sortField", "pay_time");
					_map.put("overTime", 1);
					_map.put("sortOrder", "desc");
					Order order = orderService.selectOrderByGoodsId(_map);
					if(order != null){
						isBuy = true;
						if(order.getIsFree() == 1){
							isFree = true;
						}
					}
					for (int i = 0; i < orderList.size(); i++) {
						OrderVo orderVo = orderList.get(i);
						String relationId = orderVo.getGoodsId();
						List<GoodsRelation> goodsReList = new ArrayList<GoodsRelation>();
						goodsReList = goodsRelationService.selectByGoodsId(relationId);
						for (int j = 0; j < goodsReList.size(); j++) {
							if(orderVo.getGoodsNames() == null){
								orderVo.setGoodsNames(goodsReList.get(j).getProductName());
							}else{
								orderVo.setGoodsNames(orderVo.getGoodsNames() +","+ goodsReList.get(j).getProductName());
							}
							if(orderVo.getGoodsNums() == null){
								orderVo.setGoodsNums(goodsReList.get(j).getProductNum());
							}else{
								orderVo.setGoodsNums(orderVo.getGoodsNums() +","+ goodsReList.get(j).getProductNum());
							}
						}
					}
					
					
				}
			}
		}else{
			if(userInfo.getRoleId().equals(ROLE_AGENT)){
				hasBuy = true;
			}else{	
				Map<String, Object> rmap = new HashMap<String, Object>();
				rmap.put("goodsId",goodsId);
				rmap.put("parentId", userInfo.getUserId());
				rmap.put("orderState", 0);
				rmap.put("overTime", 1);
				rmap.put("sortField", "pay_time");
				rmap.put("sortOrder", "desc");
				Order newOrder = orderService.selectOrderByGoodsId(rmap);
				if(newOrder != null){
					hasBuy = true;
				}
			}
		}
		
		request.getSession().setAttribute("pageNum", pageNum);
		
		map.put("hasRelation", hasRelation);
		map.put("hasBuy", hasBuy);
		map.put("isFree", isFree);
		map.put("isBuy", isBuy);
		map.put("goodsVo", goodsVo);
		map.put("orderList", orderList);
		map.put("goods", goods);
		return map;
	}
	
	/**
	 * 购物车界面确认订单
	 * @param goodsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/cartHaveRelation", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> cartHaveRelation(Integer shoppingCartId,Integer useYear,Integer userNum,Integer pageNum,HttpServletRequest request) throws Exception {
		boolean hasRelation = false;
		boolean hasBuy = false;
		boolean isFree = false;
		boolean isBuy = false;
		Map<String, Object> map = new HashMap<String, Object>();
		//查询当前用户信息
		User oldUserInfo = (User) request.getSession().getAttribute("userInfo");
		User userInfo = userService.selectUserInfoByUserId(oldUserInfo.getUserId());
		Integer userId = userInfo.getUserId();
		String roleId = userInfo.getRoleId();
		List<OrderVo> orderList = new ArrayList<OrderVo>();
		
		ShoppingCart shoppingCart = shoppingCartService.selectShoppingCartByShoppingCartId(shoppingCartId);
		String goodsId = shoppingCart.getProMealId();
		//查询当前所要购买的商品的信息，判断依赖关系是否存在
		GoodsVo goodsVo = goodsService.selectGoodsVoByGoodsId(goodsId);
		List<GoodsRelation> goodsRelationList = new ArrayList<GoodsRelation>();
		goodsRelationList = goodsRelationService.selectByGoodsId(goodsId);
		for (int i = 0; i < goodsRelationList.size(); i++) {
			if(goodsVo.getGoodsNames() == null){
				goodsVo.setGoodsNames(goodsRelationList.get(i).getProductName());
			}else{
				goodsVo.setGoodsNames(goodsVo.getGoodsNames() +","+ goodsRelationList.get(i).getProductName());
			}
			if(goodsVo.getGoodsNums() == null){
				goodsVo.setGoodsNums(goodsRelationList.get(i).getProductNum());
			}else{
				goodsVo.setGoodsNums(goodsVo.getGoodsNums() +","+ goodsRelationList.get(i).getProductNum());
			}
		}
		//所依赖产品的信息
		Goods goods = new Goods();
		
		if(!goodsVo.getGoodsRalateGoods().equals("0")){
			//依赖关系存在，查询所依赖的商品是否有新购订单
			hasRelation = true;
			//根据角色不同传入不同的参数
			//个人用户
			if(roleId.equals(ROLE_PERSON)){
				goods = goodsService.selectGoodsVoByGoodsId(goodsVo.getGoodsRalateGoods());
				Map<String, Object> _map = new HashMap<String, Object>();
				_map.put("goodsId", goodsVo.getGoodsRalateGoods());
				_map.put("userId", userId);
				_map.put("roleId", ROLE_PERSON);
				orderList = orderService.relationHasOrder(_map);
				if(orderList != null && orderList.size() > 0){
					
					for (int i = 0; i < orderList.size(); i++) {
						OrderVo orderVo = orderList.get(i);
						String relationId = orderVo.getGoodsId();
						List<GoodsRelation> goodsReList = new ArrayList<GoodsRelation>();
						goodsReList = goodsRelationService.selectByGoodsId(relationId);
						for (int j = 0; j < goodsReList.size(); j++) {
							if(orderVo.getGoodsNames() == null){
								orderVo.setGoodsNames(goodsReList.get(j).getProductName());
							}else{
								orderVo.setGoodsNames(orderVo.getGoodsNames() +","+ goodsReList.get(j).getProductName());
							}
							if(orderVo.getGoodsNums() == null){
								orderVo.setGoodsNums(goodsReList.get(j).getProductNum());
							}else{
								orderVo.setGoodsNums(orderVo.getGoodsNums() +","+ goodsReList.get(j).getProductNum());
							}
						}
					}
					//依赖订单存在，判断是否是免费
					hasBuy = true;
					if(orderList.get(0).getIsFree() == 1){
						isFree = true;
					}
				}
				
			//代理商用户
			}else if(roleId.equals(ROLE_AGENT)){
				goods = goodsService.selectGoodsVoByGoodsId(goodsVo.getGoodsRalateGoods());
				Map<String, Object> _map = new HashMap<String, Object>();
				_map.put("goodsId", goodsVo.getGoodsRalateGoods());
				_map.put("userId", userId);
				_map.put("roleId", ROLE_AGENT);
				orderList = orderService.relationHasOrder(_map);
				if(orderList != null && orderList.size() > 0){
					
					for (int i = 0; i < orderList.size(); i++) {
						OrderVo orderVo = orderList.get(i);
						String relationId = orderVo.getGoodsId();
						List<GoodsRelation> goodsReList = new ArrayList<GoodsRelation>();
						goodsReList = goodsRelationService.selectByGoodsId(relationId);
						for (int j = 0; j < goodsReList.size(); j++) {
							if(orderVo.getGoodsNames() == null){
								orderVo.setGoodsNames(goodsReList.get(j).getProductName());
							}else{
								orderVo.setGoodsNames(orderVo.getGoodsNames() +","+ goodsReList.get(j).getProductName());
							}
							if(orderVo.getGoodsNums() == null){
								orderVo.setGoodsNums(goodsReList.get(j).getProductNum());
							}else{
								orderVo.setGoodsNums(orderVo.getGoodsNums() +","+ goodsReList.get(j).getProductNum());
							}
						}
					}
					//依赖订单存在，判断是否是免费
					hasBuy = true;
				}
			}else if(roleId.equals(ROLE_COMPANY)){
				Map<String, Object> _map = new HashMap<String, Object>();
				_map.put("goodsId", goodsVo.getGoodsRalateGoods());
				_map.put("userId", userId);
				_map.put("roleId", ROLE_COMPANY);
				orderList = orderService.relationHasOrder(_map);
				if(orderList != null && orderList.size() > 0){
					//依赖订单存在，判断是否是免费
					hasBuy = true;
					
					_map.put("goodsId", goodsVo.getGoodsId());
					_map.put("overTime", 1);
					_map.put("sortField", "pay_time");
					_map.put("sortOrder", "desc");
					Order order = orderService.selectOrderByGoodsId(_map);
					if(order != null){
						isBuy = true;
						if(order.getIsFree() == 1){
							isFree = true;
						}
					}
					for (int i = 0; i < orderList.size(); i++) {
						OrderVo orderVo = orderList.get(i);
						String relationId = orderVo.getGoodsId();
						List<GoodsRelation> goodsReList = new ArrayList<GoodsRelation>();
						goodsReList = goodsRelationService.selectByGoodsId(relationId);
						for (int j = 0; j < goodsReList.size(); j++) {
							if(orderVo.getGoodsNames() == null){
								orderVo.setGoodsNames(goodsReList.get(j).getProductName());
							}else{
								orderVo.setGoodsNames(orderVo.getGoodsNames() +","+ goodsReList.get(j).getProductName());
							}
							if(orderVo.getGoodsNums() == null){
								orderVo.setGoodsNums(goodsReList.get(j).getProductNum());
							}else{
								orderVo.setGoodsNums(orderVo.getGoodsNums() +","+ goodsReList.get(j).getProductNum());
							}
						}
					}
					
					
				}
			}
		}else{
			if(userInfo.getRoleId().equals(ROLE_AGENT)){
				hasBuy = true;
			}else{	
				Map<String, Object> rmap = new HashMap<String, Object>();
				rmap.put("goodsId",goodsId);
				rmap.put("parentId", userInfo.getUserId());
				rmap.put("overTime", 1);
				rmap.put("orderState", 0);
				rmap.put("sortField", "pay_time");
				rmap.put("sortOrder", "desc");
				Order newOrder = orderService.selectOrderByGoodsId(rmap);
				if(newOrder != null){
					hasBuy = true;
				}
			}
		}
		
		request.getSession().setAttribute("pageNum", pageNum);
		
		map.put("hasRelation", hasRelation);
		map.put("hasBuy", hasBuy);
		map.put("isFree", isFree);
		map.put("isBuy", isBuy);
		map.put("goodsVo", goodsVo);
		map.put("orderList", orderList);
		map.put("goods", goods);
		return map;
	}
	
	/**
	 * @return 点击去购买时判断该商品是否包含在所选择的商品中
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/checkIsContain",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkIsContain(String goodsId,Integer orderId,HttpServletRequest request){
		boolean isContain = false;
		Order order = orderService.selectOrderByOrderId(orderId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("goodsId",goodsId);
		map.put("userId", order.getUserId());
		map.put("overTime", 1);
		map.put("orderState", 0);
		map.put("sortField", "pay_time");
		map.put("sortOrder", "desc");
		Order newOrder = orderService.selectOrderByGoodsId(map);
		if(newOrder != null){
			isContain = true;
		}
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("isContain", isContain);
		returnMap.put("newOrder", newOrder);
		return returnMap;
	}
	
	/**
	 * @return 购物车数据到核对产品订单页面
	 * @throws Exception 
	 * @throws NumberFormatException 
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	
	@RequestMapping(value="/cartToCheck/{goodsId}/{useYear}/{userNum}/{userId}/{shoppingCartId}",method=RequestMethod.GET)
	public ModelAndView cartToCheck(@PathVariable String goodsId,@PathVariable Integer useYear,@PathVariable Integer userNum,@PathVariable Integer userId,@PathVariable Integer shoppingCartId,HttpServletRequest request) throws NumberFormatException, Exception{
		
		User oldUserInfo = (User) request.getSession().getAttribute("userInfo");
		User userInfo = userService.selectUserInfoByUserId(oldUserInfo.getUserId());
		
		ModelAndView mav = new ModelAndView();
		
		double pagePrice = 0.00;
		String pageUseYear = useYear.toString();
		int pageUserNum = userNum;
		double pageDiscount = 0.00;
		Supplier supplier = (Supplier) request.getSession().getAttribute("supplierInfo");
		GoodsVo goodsVo = goodsService.selectGoodsVoByGoodsId(goodsId);
		goodsVo.setUsersMin(userNum);
		goodsVo.setYearsMin(useYear);
		
		//无依赖商品
		if("0".equals(goodsVo.getGoodsRalateGoods())){
			if(useYear == 0){
				pageUseYear = "20天";
				pageUserNum = userNum;
				pagePrice = 0.00;
				pageDiscount = 0.00;
			}else if(useYear == -1){
				pageUseYear = "永久";
				pageUserNum = userNum;
				pagePrice = PriceUtil.calculatePrice(goodsVo.getGoodsPrice(), 1, userNum, goodsVo.getFeeFormula(), goodsVo.getFeeBasenum());
				if(userInfo.getRoleId().equals(ROLE_AGENT)){
					pageDiscount = (1 - supplier.getMealPrivilege()) * pagePrice;
				}
			}else{
				pageUseYear = useYear + "年";
				pageUserNum = userNum;
				pagePrice = PriceUtil.calculatePrice(goodsVo.getGoodsPrice(), useYear*12, userNum, goodsVo.getFeeFormula(), goodsVo.getFeeBasenum());
				if(userInfo.getRoleId().equals(ROLE_AGENT)){
					pageDiscount = (1 - supplier.getMealPrivilege()) * pagePrice;
				}
			}
		}else{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("goodsId", goodsVo.getGoodsRalateGoods());
			map.put("userId", userId);
			map.put("roleId", ROLE_PERSON);
			map.put("sortField", "t.pay_time");
			map.put("sortOrder", "desc");
			Order relationOrder = orderService.relationNewOrder(map).get(0);
			
			Date reOverTime = relationOrder.getOverTime();
			int reUserNum = relationOrder.getUserNum();
			
			//有依赖商品
			if(useYear == 0){
				//使用年限和到期时间
				Date overTime = SignUtil.getOvertime(5, +20, new Date());
				if(reOverTime.getTime() >= overTime.getTime()){
					pageUseYear = "20天";
				}else{
					String userLife = DateUtil.getMonth("getOverTime", new Date(),relationOrder.getOverTime());
					pageUseYear = userLife;
				}
				
				//使用人数
				int _userNum = userNum;
				if(reUserNum >= _userNum){
					pageUserNum = userNum;
				}else{
					pageUserNum = reUserNum;
				}

				pagePrice = 0.00;
				pageDiscount = 0.00;
			}else{
				int month = 0;
				//使用年限和到期时间
				Date overTime = SignUtil.getOvertime(1, +useYear, new Date());
				if(reOverTime.getTime() >= overTime.getTime()){
					pageUseYear = useYear+"年";
					month = Integer.valueOf(DateUtil.getMonth("getMonth", new Date(),overTime));
				}else{
					String userLife = DateUtil.getMonth("getOverTime", new Date(),relationOrder.getOverTime());
					pageUseYear = userLife;
					month = Integer.valueOf(DateUtil.getMonth("getMonth", new Date(),reOverTime));
				}
				//使用人数
				int _userNum = userNum;
				if(reUserNum >= _userNum){
					pageUserNum = userNum;
				}else{
					pageUserNum = reUserNum;
				}
				//价格计算
				if(month != 0){
					pagePrice = PriceUtil.calculatePrice(goodsVo.getGoodsPrice(), month, pageUserNum, goodsVo.getFeeFormula(), goodsVo.getFeeBasenum());
					if(userInfo.getRoleId().equals(ROLE_AGENT)){
						pageDiscount = (1 - supplier.getProPrivilege()) * pagePrice;
					}
				}else{
					pagePrice = 0.00;
					pageDiscount = 0.00;
				}
			}
		}
		mav.addObject("shoppingCartId", shoppingCartId);
		mav.addObject("pageUseYear", pageUseYear);
		mav.addObject("pageUserNum", pageUserNum);
		mav.addObject("pagePrice", pagePrice);
		mav.addObject("pageDiscount", pageDiscount);
		mav.addObject("goods", goodsVo);
		mav.addObject("userId", userId);//域名新生成ID
		mav.setViewName("buy/check-orders");
		return mav;
	}
	
	
	/**
	 * @return 核对产品订单到提交订单页面    免费产品购买  
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/checkToSubmit",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkToSubmit(String goodsId,Integer useYear,Integer userNum,Integer userId,Integer shoppingCartId,HttpServletRequest request) throws Exception{
		
		User oldUserInfo = (User) request.getSession().getAttribute("userInfo");
		User userInfo = userService.selectUserInfoByUserId(oldUserInfo.getUserId());
		Supplier supplier = (Supplier) request.getSession().getAttribute("supplierInfo");
		GoodsVo goodsVo = goodsService.selectGoodsVoByGoodsId(goodsId);
		
		String orderNum = CreateOrderNum.getOrderNum(userInfo.getUserId());
		String EOSresult = null;
		
		boolean b = false;
		boolean c = true;
		Order order = new Order();
		
		order.setOccurTime(new Date());
		order.setOrderNum(orderNum);//订单编号
		order.setCount(1);
		order.setGoodsId(goodsId);
		order.setBuyType(0);//0新购，1续费  2升级
		order.setParentId(userInfo.getUserId());
		order.setUserId(userId);
		order.setIsDredge(0);
		
		//无依赖商品
		if("0".equals(goodsVo.getGoodsRalateGoods())){
			if(useYear == 0){
				order.setUseLife("20天");
				order.setUserNum(userNum);
				order.setOrderMoney(0.00);
				order.setPayByAccount(0.00);
				order.setPayByOther(0.00);
				order.setPayMoney(0.00);
				order.setOverTime(SignUtil.getOvertime(5, +20, new Date()));
				order.setPayTime(new Date());
				order.setPayWayId(2);
				order.setVoucherNum("");
				order.setDiscount(0.00);
				order.setOrderState(1);
				order.setIsFree(1);
			}else{
				Double price = 0.00;
				price = PriceUtil.calculatePrice(goodsVo.getGoodsPrice(), useYear*12, userNum, goodsVo.getFeeFormula(), goodsVo.getFeeBasenum());
				
				Double discount = 0.00;
				if(userInfo.getRoleId().equals(ROLE_AGENT)){
					discount = (1 - supplier.getMealPrivilege()) * price;
				}
				order.setUseLife(useYear.toString()+'年');
				order.setUserNum(userNum);
				order.setOrderMoney(price);
				order.setDiscount(discount);
				order.setOrderState(0);
				order.setIsFree(0);
				order.setOverTime(SignUtil.getOvertime(1, +useYear, new Date()));
			}
		}else{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("goodsId", goodsVo.getGoodsRalateGoods());
			map.put("userId", userId);
			map.put("roleId", ROLE_PERSON);
			map.put("sortField", "t.pay_time");
			map.put("sortOrder", "desc");
			Order relationOrder = orderService.relationNewOrder(map).get(0);
			
			Date reOverTime = relationOrder.getOverTime();
			int reUserNum = relationOrder.getUserNum();
			
			//有依赖商品
			if(useYear == 0){
				//使用年限和到期时间
				Date overTime = SignUtil.getOvertime(5, +20, new Date());
				if(reOverTime.getTime() >= overTime.getTime()){
					order.setUseLife("20天");
					order.setOverTime(overTime);
				}else{
					String userLife = DateUtil.getMonth("getOverTime", new Date(),relationOrder.getOverTime());
					order.setUseLife(userLife);
					order.setOverTime(reOverTime);
				}
				
				//使用人数
				int _userNum = userNum;
				if(reUserNum >= _userNum){
					order.setUserNum(userNum);
				}else{
					order.setUserNum(reUserNum);
				}
				
				order.setOrderMoney(0.00);
				order.setPayByAccount(0.00);
				order.setPayByOther(0.00);
				order.setPayMoney(0.00);
				order.setOrderState(1);
				order.setPayTime(new Date());
				order.setPayWayId(2);
				order.setVoucherNum("");
				order.setIsFree(1);
			}else{
				int month = 0;
				
				//使用年限和到期时间
				Date overTime = SignUtil.getOvertime(1, +useYear, new Date());
				if(reOverTime.getTime() >= overTime.getTime()){
					order.setUseLife(useYear+"年");
					order.setOverTime(overTime);
					month = Integer.valueOf(DateUtil.getMonth("getMonth", new Date(),overTime));
				}else{
					String userLife = DateUtil.getMonth("getOverTime", new Date(),relationOrder.getOverTime());
					order.setUseLife(userLife);
					order.setOverTime(reOverTime);
					month = Integer.valueOf(DateUtil.getMonth("getMonth", new Date(),reOverTime));
				}
				
				//使用人数
				int _userNum = userNum;
				if(reUserNum >= _userNum){
					order.setUserNum(userNum);
				}else{
					order.setUserNum(reUserNum);
				}
				
				//价格计算
				double orderMoney = 0.00;
				double discount = 0.00;
				if(month != 0){
					orderMoney = PriceUtil.calculatePrice(goodsVo.getGoodsPrice(), month, userNum, goodsVo.getFeeFormula(), goodsVo.getFeeBasenum());
					if(userInfo.getRoleId().equals(ROLE_AGENT)){
						discount = (1 - supplier.getProPrivilege()) * orderMoney;
					}
					order.setOrderState(0);
				}else{
					order.setPayByAccount(0.00);
					order.setPayByOther(0.00);
					order.setPayMoney(0.00);
					order.setOrderState(1);
					order.setPayTime(new Date());
					order.setPayWayId(2);
					order.setVoucherNum("");
				}
				order.setOrderMoney(orderMoney);
				order.setDiscount(discount);
				order.setIsFree(0);
			}
		}
		
		try {
			b = orderService.insertOrder(order);
		} catch (Exception e) {
			b = false;
		}
		
		if(order.getOrderMoney() == 0){
			
			//新增一条交易记录
			Deal deal = new Deal();
			deal.setDealDate(new Date());
			deal.setDealName(goodsVo.getGoodsName());
			deal.setDealNum(order.getOrderNum());
			deal.setDealState("2");
			deal.setDisburseMoney(order.getOrderMoney());
			deal.setIncomeMoney(0.0);
			deal.setPayWayId(2);
			deal.setUserId(order.getUserId());
			deal.setParentId(userInfo.getUserId());
			deal.setIsCancel(0);
			
			try {
				c = dealService.insertDeal(deal);
			} catch (Exception e) {
				c = false;
			}
			
			//=============================收支明细增加======================================
			//交易收支明细
			Cashflow cashflow = new Cashflow();
			cashflow.setCashflowNum(createNum.createCashflowNum("2"));
			cashflow.setCreateTime(new Date());
			cashflow.setDealType(2);
			cashflow.setDisburseMoney(0.00);
			cashflow.setIncomeMoney(0.00);
			cashflow.setOrderId(order.getOrderId());
			cashflow.setPayWayId(2);
			cashflow.setThenAccount(userInfo.getAccountMoney());
			cashflow.setUserId(userInfo.getUserId());
			cashflow.setIsCancel(0);
			cashflowService.insertCashflow(cashflow);
			//============================================================================
			
			if("0".equals(goodsVo.getGoodsRalateGoods())) {
				//========================普元同步开始<套餐>====================================//
				EOSresult = eos.sendMeal(order);
				//========================普元同步结束<套餐>====================================//
			}else{
				//========================普元同步开始<产品>====================================//
				EOSresult = eos.sendProduct(order);
				//========================普元同步结束<产品>====================================//
			}
			
			if("ok".equals(EOSresult)) {
				//激活新用户
				User newUser = userService.selectUserInfoByUserId(order.getUserId());
				newUser.setIsLive("1");
				userService.updateUserByKey(newUser);
				
				//更改订单的开通状态
				Order updateOrder = orderService.selectOrderByOrderId(order.getOrderId());
				updateOrder.setIsDredge(1);//0失败  1成功
				orderService.updateOrderByOrderId(updateOrder);
			}
		}
		
		if (shoppingCartId != 0) {
			ShoppingCart shoppingCart = shoppingCartService.selectShoppingCartByShoppingCartId(shoppingCartId);
			shoppingCart.setIsDelete(-1);
			shoppingCartService.updateShoppingCart(shoppingCart);
		}
		
		Map<String, Object> cartInfo = shoppingCartService.selectShoppingCartCountByUserId(userInfo.getUserId());
		if(cartInfo.get("sumPrice") == null) cartInfo.put("sumPrice", 0.0);
		request.getSession().setAttribute("cartInfo",cartInfo);
		
		request.getSession().setAttribute("order", order);
		request.getSession().setAttribute("userInfo", userInfo);
		request.getSession().setAttribute("proMealName", goodsVo.getGoodsName());
		request.getSession().setAttribute("EOSresult", EOSresult);
		request.getSession().setAttribute("BSTCOMPANYINFO", readProperties);
		
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("orderMoney", order.getOrderMoney());
		
		if(b && c)
			map2.put("isSuccess", true);
		else 
			map2.put("isSuccess", false);
		return map2;
	}
	
	/**
	 * @return 购物车页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/shoppingCart", method = RequestMethod.GET)
	public ModelAndView shoppingCart(HttpServletRequest request) throws Exception {
		
		User user = (User)request.getSession().getAttribute("userInfo");
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("buy/shopping-cart");
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId",user.getUserId());
		
		List<ShoppingCartVo> scList = shoppingCartService.selectShoppingCartVosByUserId(user.getUserId());
		modelAndView.addObject("scList",scList);
		
		return modelAndView;
	}
	
	/**
	 * get请求    删除购物车单条信息
	 */
	@RequestMapping(value="/deleteShoppingCartByShoppingCartId/{shoppingCartId}",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView deleteShoppingCartByShoppingCartId(@PathVariable Integer shoppingCartId,HttpServletRequest request){
		/**
		 * 删除 购物车 单条信息
		 */
		ShoppingCart shoppingCart = shoppingCartService.selectShoppingCartByShoppingCartId(shoppingCartId);
		shoppingCart.setIsDelete(-1);
		
		boolean b = shoppingCartService.updateShoppingCart(shoppingCart);
		
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>)request.getSession().getAttribute("cartInfo");
		
		if(b) {
			map.put("sumNum", Integer.valueOf(map.get("sumNum").toString())-1);
			map.put("sumPrice", Double.valueOf(map.get("sumPrice").toString())-shoppingCart.getProMealPrice());
			
			request.getSession().setAttribute("cartInfo",map);
		}
		
		ModelAndView mav = new ModelAndView();
		
		mav.setViewName("buy/shopping-cart");
		mav.addObject("data", b);
		return mav;
	}
	
	/**
	 * get请求    批量删除购物车信息
	 */
	@RequestMapping(value="/deleteShoppingCartsByShoppingCartId/{shoppingCartList}",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView deleteShoppingCartsByShoppingCartId(@PathVariable String shoppingCartList,HttpServletRequest request){
		/**
		 * 批量删除 购物车 信息
		 */
		boolean b = false;
		String[] a = shoppingCartList.split(",");
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>)request.getSession().getAttribute("cartInfo");
		for(int i=0;i<a.length;i++){
			ShoppingCart shoppingCart = shoppingCartService.selectShoppingCartByShoppingCartId(Integer.parseInt(a[i]));
			shoppingCart.setIsDelete(-1);
			
			b = shoppingCartService.updateShoppingCart(shoppingCart);
			if(b) {
				map.put("sumNum", Integer.valueOf(map.get("sumNum").toString())-1);
				map.put("sumPrice", Double.valueOf(map.get("sumPrice").toString())-shoppingCart.getProMealPrice());
			}
		}
		
		request.getSession().setAttribute("cartInfo",map);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("buy/shopping-cart");
		
		if(b == true) mav.addObject("data", "success");
		else mav.addObject("data", "fail");
		
		return mav;
	}
	
	/**
	 * @return 验证代金券是否有效及代金券的金额
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkVoucherNum", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkVoucherNum(String voucherNum,String dtype,String bType,HttpServletRequest request) throws Exception {
		
		//代金券是否存在
		boolean vIsExist = false;
		//代金券状态返回值
		boolean vTypeFlag = false;
		//绑定类型返回值
		boolean bTypeFlag = false;
		//绑定信息返回值
		boolean bInfoFlag = false;
		
		//用户类型
		User userInfo = (User) request.getSession().getAttribute("userInfo");
		int userId = userInfo.getUserId();
		User user = userService.selectUserInfoByUserId(userId);
		String roleId = user.getRoleId();
		
		//判断是消费还是充值  1充值,2消费
		Integer vType = 1;
		if(dtype.equals("xf")){
			vType = 2;
		}
		
		//查询产品或者套餐的编号
		String mpNum = "";
		if(SignUtil.isNotEmpty(bType)){
			Order order = orderService.selectOrderByOrderId(Integer.valueOf(bType));
			mpNum = order.getGoodsId();
			/*if(order.getNewProId() == null){
				Meal meal = mealService.selectMealByMealId(order.getMealId());
				mpNum = meal.getMealVersion();
			}else{
				Product product = productService.selectProductByProductId(order.getNewProId());
				mpNum = product.getProductVersion();
			}*/
		}
		
		Voucher voucher = voucherService.selectVoucherByVoucherNum(voucherNum);
		Map<String, Object> map = new HashMap<String, Object>();
		if(voucher != null){
			vIsExist = true;
			
			Integer voucherType = voucher.getVoucherType();
			Integer boundType = voucher.getBoundType();
			
			if(voucherType == vType){
				vTypeFlag = true;
				//判断是消费还是充值  1充值,2消费
				if(voucherType == 1){
					
					//绑定类型  1、企业用户，2、个人用户)
					if(boundType == 1){
						
						if(roleId.equals(ROLE_COMPANY)){
							bTypeFlag = true;
							if(userId == Integer.valueOf(voucher.getBoundId())){
								bInfoFlag = true;
							}
						}
					}else if(boundType == 2){
						
						if(roleId.equals(ROLE_PERSON) || roleId.equals(ROLE_AGENT)){
							bTypeFlag = true;
							if(userId == Integer.valueOf(voucher.getBoundId())){
								bInfoFlag = true;
							}
						}
					}
				}else if(voucherType == 2){
					//绑定类型  1、企业用户，2、个人用户、3、产品序列号)
					if(boundType == 1){
						
						if(roleId.equals(ROLE_COMPANY)){
							bTypeFlag = true;
							if(userId == Integer.valueOf(voucher.getBoundId())){
								bInfoFlag = true;
							}
						}
					}else if(boundType == 2){
						
						if(roleId.equals(ROLE_PERSON) || roleId.equals(ROLE_AGENT)){
							bTypeFlag = true;
							if(userId == Integer.valueOf(voucher.getBoundId())){
								bInfoFlag = true;
							}
						}
					}else if(boundType == 3){
						bTypeFlag = true;
						if(mpNum.equals(voucher.getBoundId())){
							bInfoFlag = true;
						}
					}
				}
			}
		}
	
		map.put("vIsExist", vIsExist);
		map.put("vTypeFlag", vTypeFlag);
		map.put("bTypeFlag", bTypeFlag);
		map.put("bInfoFlag", bInfoFlag);
		map.put("voucher",voucher);
		return map;
	}
	
	/**
	 * @return 提交订单并支付页面 
	 * @throws Exception
	 */
	@RequestMapping(value = "/submitOrders", method = RequestMethod.GET)
	public ModelAndView submitOrders(HttpServletRequest request) throws Exception {
		
		Order order = (Order) request.getSession().getAttribute("order");
		User user =  (User) request.getSession().getAttribute("userInfo");
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("buy/submit-orders");
		modelAndView.addObject("order", order);
		modelAndView.addObject("userInfo", user);
		
		return modelAndView;
	}
	
	/**
	 * @return 待付款到支付页面 
	 * @throws Exception
	 */
	@RequestMapping(value = "/obligationToPay", method = RequestMethod.GET)
	public ModelAndView obligationToPay(HttpServletRequest request) throws Exception {
		Integer orderId = Integer.valueOf(request.getParameter("orderId"));
		OrderVo order = orderService.selectOrderVoByOrderId(orderId);
		
		User user =  (User) request.getSession().getAttribute("userInfo");
		request.getSession().setAttribute("order",order);
		request.getSession().setAttribute("BSTCOMPANYINFO", readProperties);
		
		ModelAndView modelAndView = new ModelAndView();
		
		modelAndView.addObject("order", order);
		modelAndView.addObject("userInfo", user);
		modelAndView.addObject("proMealName", order.getGoodsName());
		modelAndView.setViewName("buy/submit-orders");
		
		return modelAndView;
	}
	
	/**
	 * 支付
	 * @param orderId
	 * @param orderMoney
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/payOrder/{orderId}/{orderMoney}/{proMealName}/{voucher}", method = RequestMethod.GET)
	public ModelAndView payOrder(@PathVariable Integer orderId,@PathVariable Double orderMoney,@PathVariable String proMealName,
			@PathVariable String voucher,HttpServletRequest request) throws Exception {
		Order order = orderService.selectOrderByOrderId(orderId);
		double voucherMoney = 0.00;
		if(!"0".equals(voucher)) {
			Voucher v = voucherService.selectVoucherByVoucherNum(voucher);
			voucherMoney = v.getVoucherMoney();
			v.setState(1);
			voucherService.updateVoucher(v);
			order.setVoucherNum(voucher);
		}
		
		User user = (User)request.getSession().getAttribute("userInfo");
		Double accountMoney = user.getAccountMoney()-orderMoney;
		Double invoiceMoney = user.getInvoiceMoney() + orderMoney;
		String EOSresult = null;
		//账户余额更新
		user.setAccountMoney(accountMoney);
		user.setInvoiceMoney(invoiceMoney);
		userService.updateUserByKey(user);
		
		request.getSession().setAttribute("userInfo", user);
		
		Double payMoney = order.getOrderMoney() - order.getDiscount() - voucherMoney;
		if(payMoney < 0) payMoney = 0.00;
		order.setPayMoney(payMoney);
		
		Double payByAccount = order.getOrderMoney() - order.getDiscount() - voucherMoney;
		if(payByAccount < 0) payByAccount = 0.00;
		order.setPayByAccount(payByAccount);
		order.setPayByOther(0.00);
		order.setOrderState(1);
		order.setPayTime(new Date());
		order.setPayWayId(2);
		
		orderService.updateOrderByOrderId(order);
		request.getSession().setAttribute("order", order);
		
		
		//增加交易信息
		Deal deal = new Deal();
		deal.setDealDate(new Date());
		deal.setDealName(proMealName);
		deal.setDealNum(order.getOrderNum());
		deal.setDealState("2");
		
		Double disburseMoney = order.getOrderMoney()- order.getDiscount()-voucherMoney;
		if(disburseMoney < 0) disburseMoney = 0.00;
		deal.setDisburseMoney(disburseMoney);
		deal.setIncomeMoney(0.0);
		deal.setPayWayId(2);
		deal.setUserId(order.getUserId());
		deal.setParentId(user.getUserId());
		deal.setIsCancel(0);
		dealService.insertDeal(deal);
		
		//=============================收支明细增加======================================
		//交易收支明细
		Cashflow cashflow = new Cashflow();
		cashflow.setCashflowNum(createNum.createCashflowNum("2"));
		cashflow.setCreateTime(new Date());
		cashflow.setDealType(2);
		
		Double c_disburseMoney = order.getOrderMoney()- order.getDiscount()-voucherMoney;
		if(c_disburseMoney < 0) c_disburseMoney = 0.00;
		cashflow.setDisburseMoney(c_disburseMoney);
		cashflow.setIncomeMoney(0.00);
		cashflow.setOrderId(order.getOrderId());
		cashflow.setPayWayId(2);
		cashflow.setThenAccount(user.getAccountMoney());
		cashflow.setUserId(user.getUserId());
		cashflow.setIsCancel(0);
		cashflowService.insertCashflow(cashflow);
		//============================================================================
		Goods goods = goodsService.selectByGoodsId(order.getGoodsId());
		if(order.getBuyType() == 0) {
			if("0".equals(goods.getGoodsRalateGoods())) {
				//========================普元同步开始<套餐>====================================//
				EOSresult = eos.sendMeal(order);
				//========================普元同步结束<套餐>====================================//
			}else{
				//========================普元同步开始<产品>====================================//
				EOSresult = eos.sendProduct(order);
				//========================普元同步结束<产品>====================================//
			}
		}else {
			EOSresult = eos.sendProOrMeal(order);
		}
		
		if("ok".equals(EOSresult)) {
			if(order.getBuyType() == 0) {
				//激活新用户
				User newUser = userService.selectUserInfoByUserId(order.getUserId());
				newUser.setIsLive("1");
				userService.updateUserByKey(newUser);
			}
			
			//更改订单的开通状态
			Order updateOrder = orderService.selectOrderByOrderId(order.getOrderId());
			updateOrder.setIsDredge(1);//0失败  1成功
			orderService.updateOrderByOrderId(updateOrder);
		}
		
		request.getSession().setAttribute("EOSresult", EOSresult);
		
		return new ModelAndView("redirect:/buy/successOrder");
	}
	
	/**
	 * @return 成功页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/successOrder", method = RequestMethod.GET)
	public ModelAndView successOrder(HttpServletRequest request) throws Exception {
		
		String EOSresult = (String) request.getSession().getAttribute("EOSresult");
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("payWayName", "账户余额支付");
		modelAndView.addObject("EOSresult", EOSresult);
		Order order = (Order) request.getSession().getAttribute("order");
		modelAndView.addObject("order", order);
		if(order.getBuyType() == 0) {
			modelAndView.setViewName("buy/success-order_byaccount");
		}else {
			modelAndView.setViewName("users/myservice/uporders_success");
		}
		return modelAndView;
	}
	
	/**
	 * 两种方式支付
	 * @param orderId
	 * @param orderMoney
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/payOrderByTwo/{orderId}/{payByAccountMoney}/{payByOther}/{proMealName}/{voucher}", method = RequestMethod.GET)
	public ModelAndView payOrderByTwo(@PathVariable Integer orderId,@PathVariable Double payByAccountMoney,
			@PathVariable Double payByOther,@PathVariable String proMealName,@PathVariable String voucher,
			HttpServletRequest request) throws Exception {
		User user = (User)request.getSession().getAttribute("userInfo");
		Double accountMoney = user.getAccountMoney()-payByAccountMoney;
		Double invoiceMoney = user.getInvoiceMoney() + payByAccountMoney;
		//账户余额更新
		user.setAccountMoney(accountMoney);
		user.setInvoiceMoney(invoiceMoney);
		userService.updateUserByKey(user);
		
		request.getSession().setAttribute("userInfo", user);
		
		//修改代金券状态
		if(!voucher.equals(0)){
			Voucher v = voucherService.selectVoucherByVoucherNum(voucher);
			v.setState(1);
			voucherService.updateVoucher(v);
		}
		
		//查询订单信息
		Order order = orderService.selectOrderByOrderId(orderId);
		
		return new ModelAndView("redirect:/alipay/doPay?orderNum="+order.getOrderNum()+"&orderMoney="+payByOther+"&userId="+order.getUserId()+"&proMealName="+proMealName+"&orderId="+orderId);
		
	}

	/**
	 * @return 发送邮件给客户  以及本公司
	 * @throws Exception
	 */
	@RequestMapping(value = "/orderSendEmailToUser", method = RequestMethod.POST)
	@ResponseBody
	public Boolean orderSendEmailToUser(String orderLinkEmail,String loginUserUnitAllName,String orderLinkMan,String orderLinkPhone,
			String proMealName,Integer orderId,String voucherNum,HttpServletRequest request ) throws Exception {
		
		boolean a = false;
		boolean b = false;
		boolean c = false;
		boolean e = false;
		
		User user = (User) request.getSession().getAttribute("userInfo");
		String userInfoName = "";
		if(SignUtil.isEmpty(user.getUserEmail())){
			userInfoName = user.getUserTel();
		}else{
			userInfoName = user.getUserEmail();
		}
		
		Order order = orderService.selectOrderByOrderId(orderId);
		order.setPayWayId(4);
		
		Double orderMoney = order.getOrderMoney();
		
		//代理商
		Supplier supplier = (Supplier) request.getSession().getAttribute("supplierInfo");
		
		DecimalFormat decimalFormat = new DecimalFormat("#0.00");
		String mealPrivilege = "1";
		String proPrivilege = "1";
		if(supplier != null && supplier.getIsValid() == 1){
			mealPrivilege = decimalFormat.format(supplier.getMealPrivilege());
			proPrivilege = decimalFormat.format(supplier.getProPrivilege());
		}
		if(order.getNewProId() == null)
			order.setDiscount(Double.valueOf(orderMoney - Double.valueOf(mealPrivilege)*orderMoney));
		else
			order.setDiscount(Double.valueOf(orderMoney - Double.valueOf(proPrivilege)*orderMoney));
		
		orderMoney = Double.valueOf(mealPrivilege)*orderMoney;
		//代金券
		if(!"0".equals(voucherNum)){
			
			Voucher voucher = voucherService.selectVoucherByVoucherNum(voucherNum);
			voucher.setState(1);
			voucherService.updateVoucher(voucher);
			
			order.setVoucherNum(voucherNum);
			orderMoney = orderMoney - voucher.getVoucherMoney();
		}
		
		a = orderService.updateOrderByOrderId(order);
		
		User newuser = userService.selectUserInfoByUserId(user.getUserId());
		Double accountMoney = newuser.getAccountMoney();
		Double invoiceMoney = newuser.getInvoiceMoney() + accountMoney;
		
		orderMoney = orderMoney - accountMoney;
		//账户余额更新
		user.setAccountMoney(0.00);
		user.setInvoiceMoney(invoiceMoney);
		userService.updateUserByKey(user);
		
		request.getSession().setAttribute("userInfo", user);
		
		
		//给客户发邮件  {"用户名","套餐名","注册账号","订单编号","产品名称","实付金额","付款单位全称","付款单位联系人","付款单位联系电话", "收款单位全称","收款单位开户行","收款单位账号","收款单位服务电话"}
		Email emailTemp = emailService.selectEmail(34);
    	String content = emailTemp.getEmailContent();
    	content = content.replace("arg0", userInfoName).replace("arg1", proMealName).
    			replace("arg2", order.getOrderNum()).replace("arg3", orderMoney.toString()).
    			replace("arg4", loginUserUnitAllName).replace("arg5", orderLinkMan).replace("arg6", orderLinkPhone).replace("arg7", readProperties.getBstCompanyName()).
    			replace("arg8", readProperties.getBstBankNname()).replace("arg9", readProperties.getBstAccount()).replace("arg10", readProperties.getBstServiceTel());
    	b = EmailUtil.sendMail(orderLinkEmail, emailTemp.getEmailSubject(), content+emailTemp.getEmailSign());
		
//		b = EmailUtil.sendMailBuyOutline(orderLinkEmail,new String[]{userInfoName,proMealName,userInfoName,order.getOrderNum(),proMealName,orderMoney.toString(),loginUserUnitAllName,orderLinkMan,orderLinkPhone,readProperties.getBstCompanyName(),readProperties.getBstBankNname(),readProperties.getBstAccount(),readProperties.getBstServiceTel()});
		
		//公司发邮件       {"客户邮箱","注册账号","订单编号","产品名称","实付金额","付款单位全称","付款单位联系人","付款单位联系电话","收款单位全称", "收款单位开户行","收款单位账号","收款单位服务电话"}
    	Email emailTemp1 = emailService.selectEmail(39);
    	String content1 = emailTemp1.getEmailContent();
    	content1 = content1.replace("arg0", orderLinkEmail).replace("arg1", userInfoName).
    			replace("arg2", order.getOrderNum()).replace("arg3", proMealName).replace("arg4", orderMoney.toString()).
    			replace("arg5", loginUserUnitAllName).replace("arg6", orderLinkMan).replace("arg7", orderLinkPhone).replace("arg8", readProperties.getBstCompanyName()).
    			replace("arg9", readProperties.getBstBankNname()).replace("arg10", readProperties.getBstAccount()).replace("arg11", readProperties.getBstServiceTel());
    	c = EmailUtil.sendMail(readProperties.getBstCWEmail(), emailTemp1.getEmailSubject(), content1+emailTemp1.getEmailSign());
    	
//    	c = EmailUtil.sendMailBSTNewOrder(readProperties.getBstCWEmail(),new String[]{orderLinkEmail,userInfoName,order.getOrderNum(),proMealName,orderMoney.toString(),loginUserUnitAllName,orderLinkMan,orderLinkPhone,readProperties.getBstCompanyName(),readProperties.getBstBankNname(),readProperties.getBstAccount(),readProperties.getBstServiceTel()});
		
		//新增线下支付记录
		Payment payment = new Payment();
		payment.setPaymentNum(createNum.createPaymentNum("2"));
		payment.setUserId(user.getUserId());
		payment.setAttachIds("");
		payment.setCreateTime(new Date());
		payment.setDealType(2);
		payment.setLinkMan(orderLinkMan);
		payment.setLinkTell(orderLinkPhone);
		payment.setOrderId(orderId);
		payment.setPaymentState(0);
		payment.setRemitMoney(orderMoney);
		payment.setRemitCompany(loginUserUnitAllName);
		payment.setIsCancel(0);
		
		e = paymentService.insertPayment(payment);
		
		if(a && b && c && e){
			return true;
		} else{
			return false;
		}
	}

	/**
	 * @return 添加
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/haveMealsNum",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> haveMealsNum(HttpServletRequest request){
		User user = (User)request.getSession().getAttribute("userInfo");
		
		Map<String, Object> _map = new HashMap<String, Object>();
		_map.put("userId",user.getUserId());
		_map.put("isYun",user.getIsYun());
		_map.put("isYun",user.getIsYun());
		
		List<OrderVo> orderVoList = orderService.selectMealsNumByCondition(_map);
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("orderVoList",orderVoList);
		request.getSession().setAttribute("userMealInfo", orderVoList);
		return map;
	}
}


